package com.young4j.xinsuiwutuobang.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PropsUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(PropsUtils.class);
	/**
	 * 加载属性文件
	 * 通过Thread类获取当前线程的类加载上下文，将文件转换为流
	 * 如果获取的输入流为空，则抛出运行时异常
	 * @param fileName
	 * @return
	 */
	public static Properties loadProps(String fileName){
		Properties props = null;
		InputStream is = null;
		try {
			is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
			if(is == null){
				throw new FileNotFoundException(fileName + "file is not find");
			}
			props = new Properties();
			props.load(is);
		} catch (IOException e) {
			LOGGER.error("load properties file failure",e);
		}finally{
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					LOGGER.error("close inputStream failure",e);
				}
			}
		}
		return props;
	}
	/**
	 * 获取文件属性信息
	 * 如果属性文件不包含key，则给一个默认值，默认值通过重载方法添加
	 * 属性的value默认为字符串，通过props.containsKey(key)来判断是否包含此key
	 * 通过props.getProperty(key)获取属性parse成相应的类型
	 * @param props
	 * @param key
	 * @return
	 */
	public static String getString(Properties props,String key){
		return getString(props,key,"");
	}
	public static String getString(Properties props,String key,String defaultValue){
		String value = defaultValue;
		if(props.containsKey(key)){
			value = props.getProperty(key);
		}
		return value;
	}
	public static int getInt(Properties props,String key){
		return getInt(props,key,0);
	}
	public static int getInt(Properties props,String key,int defaultValue){
		int value = defaultValue;
		if(props.containsKey(key)){
			value = Custutils.parseInt(props.getProperty(key));
		}
		return value;
	}
	public static boolean getBoolean (Properties props,String key){
		return getBoolean(props,key,false);
	}
	public static boolean getBoolean(Properties props,String key,boolean defaultValue){
		boolean value = defaultValue;
		if(props.containsKey(key)){
			value = Custutils.parseBoolean(props.getProperty(key));
		}
		return value;
	}
	
}
